package com.example.service.impl;

import ch.qos.logback.classic.Logger;
import com.example.entity.*;
import com.example.mapp.PointFlowMapp;
import com.example.mapp.SpotCheckItemMapp;
import com.example.mapp.SpotCheckPlanMapp;
import com.example.mapp.SpotObjectPlanMapp;
import com.example.service.SpotCheckItemService;
import com.example.util.DateUtils;
import com.example.util.ResultUtil;
import com.example.util.StringUtil;
import com.example.util.SystemPointUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 实施对象
 */
@Service
public class SpotCheckItemServiceImpl implements SpotCheckItemService {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(SpotCheckItemServiceImpl.class);

	@Autowired
	private SpotCheckItemMapp spotCheckItemMapp;

	@Autowired
	private SpotCheckPlanMapp spotCheckPlanMapp;


	@Autowired
	private SpotObjectPlanMapp spotObjectPlanMapp;

	@Autowired
	private PointFlowMapp pointFlowMapp;




	@Override
	@Transactional
	public Map<String, Object> insert(Map map) {
		String message = "添加成功";
		Map<String, Object> resultMap = new HashMap<>();
		try {
		 	String planInfo = (String)map.get("planInfo");
			List<String> plans = Arrays.asList(planInfo.split(","));

			// 先进行查询，表里是否存在计划表的检查项
			if (plans != null && plans.size() > 0) {
				for (String planId : plans) {
					SpotCheckItem checkItem = new SpotCheckItem();
					checkItem.setId(Long.valueOf(planId));
					List<SpotCheckItem> itemIds = spotCheckItemMapp.findList(checkItem);
					if (itemIds != null && itemIds.size() > 0) {
						// 进行删除
						spotCheckItemMapp.delete(Long.valueOf(planId));
					}
				}
			}

			// 获取检查项
			String lists =(String)map.get("updateList");
			List<String> itemList = Arrays.asList(lists.split(","));

			// 获取自定义项
			String customs=(String)map.get("custom");
			List<String> customList = Arrays.asList(customs.split(","));

			for (String planId : plans) {
				for (String item : itemList) {
					SpotCheckItem checkItem = new SpotCheckItem();
					checkItem.setItemId(Long.valueOf(item));
					checkItem.setPlanId(Long.valueOf(planId));
					checkItem.setIsCustom("N");

					spotCheckItemMapp.insert(checkItem);
				}

				if (customList != null && customList.size() > 0) {
					for (String name : customList) {

						if (StringUtil.isNotBlank(name)) {

							SpotCheckItem checkItem = new SpotCheckItem();
							checkItem.setPlanId(Long.valueOf(planId));
							checkItem.setIsCustom("Y");
							checkItem.setCustomName(name);

							spotCheckItemMapp.insert(checkItem);
						}
					}
				}
			}


			for (String planId : plans) {
				// 保存数据之后，更新主表的检查字段
				SpotCheckPlan spotCheckPlan = new SpotCheckPlan();
				spotCheckPlan.setIsCheck("Y");
				spotCheckPlan.setId(Long.valueOf(planId));
				spotCheckPlanMapp.updateIsCheck(spotCheckPlan);
			}


		}catch (Exception e){
			logger.error(e.getMessage());
			message = "添加失败";
			return ResultUtil.returnError(message + e.getMessage(), null);
		}
		return ResultUtil.returnSuccess(message, resultMap);
	}

	@Override
	public Map<String, Object> findList(Map map) {
		String message = "查询成功";
		List<SpotCheckItem> list = new ArrayList<>();
		try{
			SpotCheckItem spotCheckItem = new SpotCheckItem();

			Integer planId = (Integer) map.get("planId");
			spotCheckItem.setPlanId(Long.valueOf(planId));


			list = spotCheckItemMapp.findList(spotCheckItem);

		}catch (Exception e){
			logger.error(e.getMessage());
			message = "添加失败";
			return ResultUtil.returnError(message + e.getMessage(), list);
		}
		return ResultUtil.returnSuccess(message, list);
	}

	/**
	 * 批量删除自定义维保项
	 * @param map
	 * @return
	 */
	@Override
	@Transactional
	public Map<String, Object> deleteById(Map map) {

		String message = "删除成功";
		List<SpotCheckItem> list = new ArrayList<>();
		try {
			if (map != null && map.size() > 0) {
				String ids = (String) map.get("ids");

				List<String> idList = Arrays.asList(ids.split(","));

				for (String id : idList) {

					spotCheckItemMapp.deleteById(Long.valueOf(id));
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			message = "删除失败";
			return ResultUtil.returnError(message + e.getMessage(), list);
		}
		return ResultUtil.returnSuccess(message, list);
	}

	/**
	 *App端查询检查项数据
	 * @param map
	 * @return
	 */

	@Override
	public Map<String, Object> findCheckItemApp(Map map) {
		String message = "查询成功";
		List<Map<String,Object>> list = new ArrayList<>();
		try{
			if (map != null && map.size() > 0) {
				list = spotCheckItemMapp.findCheckItemApp(map);
				if (list != null && list.size() > 0) {
					for (Map<String, Object> objectMap : list) {
						objectMap.put("isChecked", "0");

						Map<String,Object> objectMapPic = new HashMap<>();
						List<Map<String,Object>> listPic = new ArrayList<>();
						objectMapPic.put("picUrl",listPic);

						objectMap.put("result",objectMapPic);
					}
				}
			}
		}catch (Exception e){
			logger.error(e.getMessage());
			message = "查询失败";
			return ResultUtil.returnError(message + e.getMessage(), list);
		}
		return ResultUtil.returnSuccess(message, list);
	}

	/**
	 * app端保存检查项
	 */
	@Override
	@Transactional
	public Map<String, Object> addCheckItemApp(Map map) {
		String message = "新增成功";

		List<SpotObjectCensus> intoParam = new ArrayList<>();

		// 获取几台电梯
		int num = 0;

		try{
			if (map != null && map.size() > 0) {
				// 获取数据
				List<Map<String, Object>> param = (List<Map<String, Object>>) map.get("list");
				if (param != null && param.size() > 0) {

					num = param.size();

					for (Map<String, Object> objectMap : param) {

						// 获取电梯设备Id
						String elevatorId = (String) objectMap.get("name");
						// 获取计划Id
						Integer planId=null;
						// 获取录入人
						String createBy = (String) objectMap.get("createBy");

						// 获取检查项
						List<Map<String, Object>> lists = (List<Map<String, Object>>) objectMap.get("project");
						if (lists != null && lists.size() > 0) {

							planId = (Integer) lists.get(0).get("planId");
							Integer implementObjectId = (Integer) lists.get(0).get("implementObjectId");

							// 获取检查结果的三项数据
							String resultEvaluate = (String) lists.get(0).get("resultEvaluate");
							String opinion = (String) lists.get(0).get("opinion");


							// 获取数据转换成entry
							for (Map<String, Object> objlist : lists) {
								SpotObjectCensus objectCensus = new SpotObjectCensus();


								objectCensus.setResultEvaluate(resultEvaluate);
								objectCensus.setOpinion(opinion);

								objectCensus.setPlanId(Long.valueOf(planId));
								String isChecked = (String) objlist.get("isChecked");
								// 判断 0 、2 表示没有说明
								if(! "1".equals(isChecked)){
									objectCensus.setRemarkes("");
                                    objectCensus.setPicUrl("");
								}else{
									objectCensus.setRemarkes((String) objlist.get("remarkes"));
                                    // 保存照片
                                    String picUrl = (String) objlist.get("picUrl");
                                    if(StringUtil.isNotBlank(picUrl)){
                                        objectCensus.setPicUrl(picUrl);
                                    }else{
                                        objectCensus.setPicUrl("");
                                    }
								}

								Integer checkItemId = (Integer) objlist.get("checkItemId");
								objectCensus.setCheckItemId(Long.valueOf(checkItemId));

								objectCensus.setCheckRecord(isChecked);
								objectCensus.setElevatorId(elevatorId);
								if((Integer)objlist.get("iteId") !=null){

									objectCensus.setCheckItemId(Long.valueOf((Integer)objlist.get("iteId")));
								}
								objectCensus.setCheckItemName(((String) objlist.get("checkName")).trim());
								objectCensus.setDelFlag("1");
								objectCensus.setCreateDate(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
								objectCensus.setCheckMan((String) map.get("checkMan"));
								objectCensus.setHeadMan((String) map.get("headMan"));
								objectCensus.setImplementObject((String) map.get("implementObject"));
								objectCensus.setUserId(Long.valueOf((Integer) map.get("userId")));
								objectCensus.setObjId(Long.valueOf((Integer) map.get("objId")));
								objectCensus.setSignPhoto((String) map.get("signPhoto"));
								objectCensus.setCreateBy(createBy);

								intoParam.add(objectCensus);
							}
							// 删除缓存表数据
							SpotCheckCache checkCache = new SpotCheckCache();
							checkCache.setImplementObjectId(Long.valueOf(implementObjectId));
							checkCache.setPlanId(Long.valueOf(planId));

							spotCheckItemMapp.deleteCache(checkCache);


						}
					}

					// 保存数据
					if(intoParam !=null && intoParam.size()>0){
						for (SpotObjectCensus object:intoParam){
							spotCheckItemMapp.addCheckItemApp(object);
						}
					}

					// 修改标志
					Long obj = Long.valueOf ((Integer) map.get("objId"));
					if(obj !=null){
						SpotObjectPlan plan = new SpotObjectPlan();
						plan.setId(obj);
						plan.setCheckRecord("1");

						spotObjectPlanMapp.updateCheckRecord(plan);
					}
				}
			}
		}catch (Exception e){
			logger.error(e.getMessage());
			message = "新增失败";
			return ResultUtil.returnError(message + e.getMessage(), intoParam);
		}finally {
			// 当电梯数据不为0时
			if (num != 0) {
				// 获取维保质量检查缓存
				PointDefendInfoCache infoCache = new PointDefendInfoCache();
				PointDefend defend = infoCache.getKeyByValue("maintenance_quality_check_records");

				// 获取当前用户，计算积分
				Long userId = Long.parseLong(map.get("userId").toString());
				Map<String, Object> maps = pointFlowMapp.findUserInfoByUserId(userId);
				long mark = (long) maps.get("mark");
				int round = (int) (mark + defend.getMark() * num);

				// 更新用户信息总积分
				String userIds = maps.get("userId").toString();
				int i1 = pointFlowMapp.updateMark(round, userIds);

				String userName = maps.get("userName").toString();
				String partyName = maps.get("partyName").toString();
				SystemPointUtil.insertFlow(pointFlowMapp, i1, defend, round, userName, partyName, "提交一台维保质量检查记录");
			}
		}
		return ResultUtil.returnSuccess(message, intoParam);
	}

	/**
	 * 获取电梯信息
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> findElevatorInfoApp(Map map) {
		String message = "查询成功";
		List<Map<String,Object>> list = new ArrayList<>();
		try{
			if (map != null && map.size() > 0) {
				list = spotCheckItemMapp.findElevatorInfoApp(map);
			}
		}catch (Exception e){
			logger.error(e.getMessage());
			message = "查询失败";
			return ResultUtil.returnError(message + e.getMessage(), list);
		}
		return ResultUtil.returnSuccess(message, list);
	}

	/**
	 * 多个电梯的缓存表
	 * @param map
	 * @return
	 */
	@Override
	public Map<String, Object> querySpotCheckCacheApp(Map map) {

		String message = "查询成功";
		Map<String, List<Map<String, Object>>> list = new HashMap<>();
		boolean flag = true;
		try{
			if (map != null && map.size() > 0) {
				// 先查询根据 设备Id以及计划Id
				SpotCheckCache cache = new SpotCheckCache();
				String name = (String) map.get("name");
				cache.setName(name);
				String createBy = (String) map.get("createBy");
				cache.setCreateBy(createBy);
				List<Map<String, Object>> projectmap = (List<Map<String, Object>>) map.get("project");
				Integer planId = (Integer) projectmap.get(0).get("planId");
				cache.setPlanId(Long.valueOf(planId));
				String implementObjectId = (String) map.get("implementObjectId");
				cache.setImplementObjectId(Long.valueOf(implementObjectId));
				List<Map<String, Object>> mapList = spotCheckItemMapp.returnFindCache(cache);
				if (mapList != null && mapList.size() > 0) {
					//return ResultUtil.returnError("此电梯已经存在检查列表中，请重新扫描！", list);
					flag = false;
				}
				// 当查询到数据flag为false，不进行数据保存，防止重复
				if(flag){
					// 获取检查结果的三项数据
					String resultEvaluate = (String) map.get("resultEvaluate");
					String opinion = (String) map.get("opinion");


					for (Map<String, Object> mapinsert : projectmap) {
						SpotCheckCache spotCheckCache = new SpotCheckCache();
						spotCheckCache.setName(name);
						spotCheckCache.setCreateBy(createBy);
						spotCheckCache.setResultEvaluate(resultEvaluate);
						spotCheckCache.setOpinion(opinion);

						spotCheckCache.setImplementObjectId(Long.valueOf(implementObjectId));
						Integer iteId = (Integer) mapinsert.get("iteId");
						if(iteId !=null){
							spotCheckCache.setCheckItemId(Long.valueOf(iteId));
						}else{
							spotCheckCache.setCheckItemId(Long.valueOf(0));
						}

						spotCheckCache.setSpotCheckItemId(Long.valueOf((Integer) mapinsert.get("id")));
						spotCheckCache.setCheckName(((String) mapinsert.get("checkName")).trim());
						spotCheckCache.setIsChecked((String) mapinsert.get("isChecked"));
						spotCheckCache.setPlanId(Long.valueOf((Integer) mapinsert.get("planId")));

						String remarkes = (String) mapinsert.get("remarkes");
						if(StringUtil.isNotBlank(remarkes)){
							spotCheckCache.setRemarkes(remarkes);
						}else{
							spotCheckCache.setRemarkes("");
						}

						// 获取照片
						Map<String, Object> result = (Map<String, Object>) mapinsert.get("result");
						List<String> picUrlList = (List<String>) result.get("picUrl");
						if (picUrlList != null && picUrlList.size() > 0) {
							spotCheckCache.setPicUrl(StringUtil.join(picUrlList, ","));
						} else {
							spotCheckCache.setPicUrl("");
						}
						// 数据先新增
						spotCheckItemMapp.insertCache(spotCheckCache);
					}
				}

				SpotCheckCache checkCache = new SpotCheckCache();
				checkCache.setCreateBy(createBy);
				checkCache.setPlanId(Long.valueOf(planId));
				checkCache.setImplementObjectId(Long.valueOf(implementObjectId));
				List<Map<String,Object>> objectList = spotCheckItemMapp.returnFindCache(checkCache);

				// 数据封装，然后返回
				if (objectList != null && objectList.size() > 0) {

					for (Map<String, Object> objectMap : objectList) {
						String elename = (String) objectMap.get("name");

						Map<String,Object> stringObjectList = new HashMap<>();
						String picUrl = (String) objectMap.get("picUrl");

						List<String> split = new ArrayList<>();
						if(StringUtil.isNotBlank(picUrl)){
							split =Arrays.asList(picUrl.split(","));

						}
						stringObjectList.put("picUrl",split);
						objectMap.put("result",stringObjectList);

						if (list.containsKey(elename) && list.size() > 0) {
							list.get(elename).add(objectMap);
						} else {
							List<Map<String, Object>> paramList = new ArrayList<>();
							paramList.add(objectMap);
							list.put(elename, paramList);
						}
					}
				}
				// 为false时是重复数据，返回的成功码不能是200
				if(! flag){
					return ResultUtil.returnError(message, list);
				}
			}
		}catch (Exception e){
			logger.error(e.getMessage());
			message = "查询失败";
			return ResultUtil.returnError(message + e.getMessage(), list);
		}
		return ResultUtil.returnSuccess(message, list);
	}

}
